package com.example.note.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

public class HandwritingView extends View {
    
    private Paint paint;
    private Path currentPath;
    private List<PathPaint> paths;
    private Canvas drawCanvas;
    private Bitmap canvasBitmap;
    private int paintColor = Color.BLACK;
    private float brushSize = 5f;
    private boolean isReadOnly = false; // 添加只读模式标志
    private Bitmap pendingBitmap; // 待加载的bitmap
    
    private static class PathPaint {
        Path path;
        Paint paint;
        
        PathPaint(Path path, Paint paint) {
            this.path = new Path(path);
            this.paint = new Paint(paint);
        }
    }
    
    public HandwritingView(Context context) {
        super(context);
        init();
    }
    
    public HandwritingView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }
    
    public HandwritingView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }
    
    private void init() {
        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setDither(true);
        paint.setColor(paintColor);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeJoin(Paint.Join.ROUND);
        paint.setStrokeCap(Paint.Cap.ROUND);
        paint.setStrokeWidth(brushSize);
        
        currentPath = new Path();
        paths = new ArrayList<>();
    }
    
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        canvasBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        drawCanvas = new Canvas(canvasBitmap);
        drawCanvas.drawColor(Color.WHITE);
        
        // 如果有待加载的bitmap，现在加载它
        if (pendingBitmap != null) {
            Log.d("HandwritingView", "onSizeChanged中加载待处理的bitmap");
            Bitmap bitmapToLoad = pendingBitmap;
            pendingBitmap = null; // 清除引用
            loadFromBitmap(bitmapToLoad);
        }
    }
    
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        
        // 绘制背景
        canvas.drawBitmap(canvasBitmap, 0, 0, null);
        
        // 绘制所有路径
        for (PathPaint pathPaint : paths) {
            canvas.drawPath(pathPaint.path, pathPaint.paint);
        }
        
        // 绘制当前路径
        canvas.drawPath(currentPath, paint);
    }
    
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // 如果是只读模式，不处理触摸事件
        if (isReadOnly) {
            return false;
        }
        
        float x = event.getX();
        float y = event.getY();
        
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // 请求父容器不要拦截触摸事件
                getParent().requestDisallowInterceptTouchEvent(true);
                currentPath.moveTo(x, y);
                return true;
                
            case MotionEvent.ACTION_MOVE:
                // 继续请求父容器不要拦截触摸事件
                getParent().requestDisallowInterceptTouchEvent(true);
                currentPath.lineTo(x, y);
                invalidate();
                return true;
                
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                // 允许父容器重新拦截触摸事件
                getParent().requestDisallowInterceptTouchEvent(false);
                // 保存当前路径
                paths.add(new PathPaint(currentPath, paint));
                drawCanvas.drawPath(currentPath, paint);
                currentPath = new Path();
                invalidate();
                return true;
                
            default:
                return false;
        }
    }
    
    // 清除画布
    public void clearCanvas() {
        paths.clear();
        currentPath.reset();
        if (drawCanvas != null) {
            drawCanvas.drawColor(Color.WHITE, PorterDuff.Mode.CLEAR);
            drawCanvas.drawColor(Color.WHITE);
        }
        invalidate();
    }
    
    // 撤销上一笔
    public void undo() {
        if (!paths.isEmpty()) {
            paths.remove(paths.size() - 1);
            redrawCanvas();
            invalidate();
        }
    }
    
    // 重绘画布
    private void redrawCanvas() {
        if (drawCanvas != null) {
            drawCanvas.drawColor(Color.WHITE, PorterDuff.Mode.CLEAR);
            drawCanvas.drawColor(Color.WHITE);
            for (PathPaint pathPaint : paths) {
                drawCanvas.drawPath(pathPaint.path, pathPaint.paint);
            }
        }
    }
    
    // 设置画笔颜色
    public void setPaintColor(int color) {
        this.paintColor = color;
        paint.setColor(color);
    }
    
    // 设置画笔大小
    public void setBrushSize(float size) {
        this.brushSize = size;
        paint.setStrokeWidth(size);
    }
    
    // 获取画布内容为Bitmap
    public Bitmap getCanvasBitmap() {
        Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.WHITE);
        
        for (PathPaint pathPaint : paths) {
            canvas.drawPath(pathPaint.path, pathPaint.paint);
        }
        
        return bitmap;
    }
    
    // 检查是否有内容
    public boolean hasContent() {
        return !paths.isEmpty();
    }
    
    // 从Bitmap加载手写内容
    public void loadFromBitmap(Bitmap bitmap) {
        Log.d("HandwritingView", "loadFromBitmap被调用");
        if (bitmap == null) {
            Log.e("HandwritingView", "传入的bitmap为null");
            return;
        }
        
        Log.d("HandwritingView", "bitmap尺寸: " + bitmap.getWidth() + "x" + bitmap.getHeight());
        
        // 清除路径但不清除画布
        paths.clear();
        currentPath.reset();
        
        // 如果画布还未初始化，先强制初始化
        if (drawCanvas == null || canvasBitmap == null) {
            Log.d("HandwritingView", "画布未初始化，强制初始化");
            int width = getWidth();
            int height = getHeight();
            if (width > 0 && height > 0) {
                canvasBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
                drawCanvas = new Canvas(canvasBitmap);
                drawCanvas.drawColor(Color.WHITE);
                Log.d("HandwritingView", "强制初始化完成，画布尺寸: " + width + "x" + height);
            } else {
                Log.e("HandwritingView", "View尺寸无效: " + width + "x" + height + "，延迟加载bitmap");
                // 保存bitmap，等待View尺寸确定后再加载
                pendingBitmap = bitmap;
                return;
            }
        }
        
        // 确保画布已经初始化
        if (drawCanvas != null && canvasBitmap != null) {
            Log.d("HandwritingView", "画布已初始化，canvasBitmap尺寸: " + canvasBitmap.getWidth() + "x" + canvasBitmap.getHeight());
            // 先清除画布
            drawCanvas.drawColor(Color.WHITE);
            // 将bitmap缩放到画布大小并绘制
            drawCanvas.drawBitmap(bitmap, null, 
                new android.graphics.Rect(0, 0, canvasBitmap.getWidth(), canvasBitmap.getHeight()), null);
            Log.d("HandwritingView", "bitmap已绘制到画布，调用invalidate");
            invalidate();
        } else {
            Log.e("HandwritingView", "画布初始化失败");
        }
    }
    
    // 设置只读模式
    public void setReadOnly(boolean readOnly) {
        this.isReadOnly = readOnly;
    }
    
    // 获取只读模式状态
    public boolean isReadOnly() {
        return isReadOnly;
    }
}